//
//  SharkShoppingVC.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/10/5.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "SharkShoppingVC.h"

@interface SharkShoppingVC ()<UITextFieldDelegate>

//商品
@property (nonatomic, strong) UILabel *topTitltLabel;
@property (nonatomic, strong) UIImageView *leftImageIocn;
@property (nonatomic, strong) UILabel *shoppingTitle;
@property (nonatomic, strong) UIView *lineView;

//价格
@property (nonatomic, strong) UIView *priceBgView;
@property (nonatomic, strong) UILabel *earningsLabel;
@property (nonatomic, strong) UILabel *leftPriceLabel;
@property (nonatomic, strong) UILabel *priceLabel;

//店主销售价
@property (nonatomic, strong) UIView *landlordBgView;
@property (nonatomic, strong) UILabel *lastLabel;
@property (nonatomic, strong) UITextField *priceTF;
@property (nonatomic, strong) UILabel * sectionLabel;

//图文
@property (nonatomic, strong) UIView *btnBgView;
@property (nonatomic, strong) UIButton *imageTextBtn;
@property (nonatomic, strong) UIButton *moreSharkBtn;
@property (nonatomic, strong) UIButton *shoppingSharkBtn;

@property (nonatomic, assign) CGFloat f_shopCostPrice;//店铺成本价
@property (nonatomic, assign) CGFloat f_marketPrice;//市场划价线
//@property (nonatomic, assign) CGFloat f_suggestShopPrice;//建议零售价
@property (nonatomic, assign) CGFloat f_oldPrice;//记录上一次的店铺售卖价
@property (nonatomic, assign) CGFloat f_newPrice;//修改后最新的销售价

@property (nonatomic, strong) SharkShoppingModel *sharkModel;//
@property (nonatomic, strong) NSMutableArray *templatesArray;//模板数组
@property (nonatomic, copy) NSString *template_id;//模板id

@end

@implementation SharkShoppingVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (NSMutableArray *)templatesArray
{
    if (_templatesArray == nil)
    {
        _templatesArray = [NSMutableArray array];
    }
    return _templatesArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //1，隐藏baseVC导航
    //2，创建商品视图
    [self createShoppingView];
    [self createPriceView];
    [self createLandlordBgView];
    [self createSharkAndCancleBtn];
    //3，请求数据
    [self httpRequestData];
}

#pragma mark - 请求数据
- (void)httpRequestData
{
    __weak SharkShoppingVC *myself = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.product_id forKey:@"itemId"];
    
    NSLog(@"商品分享-product_id-%@",self.product_id);
    [HttpRequest formPostPath:GoodsSharkPreview_API params:dic resultBlock:^(NSDictionary *Data, MsgModel *msgModel)
    {
        NSLog(@"分享商品Data--%@",Data);
        
        NSDictionary *result = (NSDictionary *)Data[@"result"];
        NSDictionary *itemDetailVO = (NSDictionary *)result[@"itemDetailVO"];
        NSArray *shareTemplateList = (NSArray *)result[@"shareTemplateList"];
        NSLog(@"分享商品itemDetailVO--%@",itemDetailVO);
        NSLog(@"分享商品shareTemplateList--%@",shareTemplateList);
        NSError *error;
        myself.sharkModel = [[SharkShoppingModel alloc] initWithDictionary:itemDetailVO error:&error];
        [myself setData];
        
        for (NSDictionary *dic in shareTemplateList)
        {
            TemplatesModel *model = [[TemplatesModel alloc] initWithDictionary:dic error:&error];
            [myself.templatesArray addObject:model];
        }
        
        [myself createShowImageTextView];
    }];
}

#pragma mark -
- (void)setData
{
    [self.leftImageIocn sd_setImageWithURL:[NSURL URLWithString:self.sharkModel.showImage] placeholderImage:[UIImage imageNamed:@"zhanwei100"]];
    self.shoppingTitle.text = [NSString stringWithFormat:@"[%@]",self.sharkModel.title];
    
    //预计收益
    CGFloat earnings = [self.sharkModel.price floatValue] - [self.sharkModel.shopCostPrice floatValue];
    self.earningsLabel.text = [NSString stringWithFormat:@"￥%0.2f",earnings];
    
    if ([self.sharkModel.isPlatForm boolValue])
    {//跨境
        //建议零售价，精确到小数点后两位
        CGFloat suggestPrice = [self.sharkModel.suggestPrice floatValue];
        //建议零售价label
        self.priceLabel.text = [NSString stringWithFormat:@"￥%0.2f",suggestPrice];
    }
    else {//自营
        
    }
    
    //店铺成本价
    self.f_shopCostPrice = [self.sharkModel.shopCostPrice floatValue];
    //市场画价线
    self.f_marketPrice = [self.sharkModel.marketPrice floatValue];
    if (self.isHide)
    {//自营隐藏掉
        self.sectionLabel.text = @"";
    }
    else {//跨境显示
        self.sectionLabel.text = [NSString stringWithFormat:@"(价格调整区间：￥%0.2f-￥%0.2f)",self.f_shopCostPrice,self.f_marketPrice];
        [self.sectionLabel sizeToFit];
    }
    
    
    CGFloat price = [self.sharkModel.price floatValue];//店主售卖价
    self.priceTF.text = [NSString stringWithFormat:@"￥%0.2f",price];
    self.priceTF.userInteractionEnabled = YES;
    [self.priceTF sizeToFit];
    //初始化价格
    self.f_newPrice = price;
    
    //        self.lastLabel.text = [NSString stringWithFormat:@"* 您上次销售价格为 ¥%0.2f 元",self.f_oldPrice];
    //        [self.lastLabel sizeToFit];
}

#pragma mark - 创建商品视图
- (void)createShoppingView
{
    self.topTitltLabel = [[UILabel alloc] init];
    [self.view addSubview:self.topTitltLabel];
    if (@available(iOS 11.0, *))
    {
        self.topTitltLabel.frame = CGRectMake(15, 60+TopStatusHeight_xs, 100, 25);
    } else {
        // Fallback on earlier versions
        self.topTitltLabel.frame = CGRectMake(15, 60+TopStatusHeight, 100, 25);
    }
    self.topTitltLabel.text = @"分享商品";
    self.topTitltLabel.textAlignment = 0;
    self.topTitltLabel.textColor = BlackTextColor;
    self.topTitltLabel.font = FontMediumWithSize(18);
    
    self.leftImageIocn = [[UIImageView alloc] init];
    [self.view addSubview:self.leftImageIocn];
    self.leftImageIocn.frame = CGRectMake(15, self.topTitltLabel.bottom+20, 65, 65);
    self.leftImageIocn.backgroundColor = GrayTextColor;
    
    self.shoppingTitle = [[UILabel alloc] init];
    [self.view addSubview:self.shoppingTitle];
    self.shoppingTitle.frame = CGRectMake(self.leftImageIocn.right+10, self.leftImageIocn.origin.y, SCREENWIDTH-25-10-self.leftImageIocn.width, 40);
    self.shoppingTitle.textColor = BlackTextColor;
    self.shoppingTitle.textAlignment = 0;
    self.shoppingTitle.font = FontWithSize(14);
    self.shoppingTitle.numberOfLines = 0;
    
    self.lineView = [[UIView alloc] initWithFrame:CGRectMake(15, self.leftImageIocn.bottom+15, SCREENWIDTH-30, 1)];
    [self.view addSubview:self.lineView];
    self.lineView.backgroundColor = GrayTextColor;
}

#pragma mark - 创建价格视图
- (void)createPriceView
{
    self.priceBgView = [[UIView alloc] init];
    [self.view addSubview:self.priceBgView];
    self.priceBgView.backgroundColor = [UIColor whiteColor];
    self.priceBgView.frame = CGRectMake(0, self.lineView.bottom, SCREENWIDTH, self.isHide == YES?0:86);
    
    CGFloat labelWidth = (SCREENWIDTH-30)/2;
    for (int i = 0; i < 4; i++)
    {
        UILabel *label = [[UILabel alloc] init];
        [self.priceBgView addSubview:label];
        label.frame = CGRectMake(15+(labelWidth+0)*(i%2), 15+(14+23)*(i/2), labelWidth, 14);
        label.font = FontWithSize(14);
        label.textColor = (i%2==1)?BlackTextColor:RGBACOLOR(154, 154, 154, 1);
        label.textAlignment = (i%2==1)?2:0;
        if (i==0) {
            label.text = @"预计收益";
        }
        else if (i == 1) {
            label.text = @"￥0.00";
            self.earningsLabel = label;
        }
        else if (i == 2) {
            label.text = @"建议零售价";
            self.leftPriceLabel = label;
        }
        else if (i == 3) {
            label.text = @"￥0.00";
            self.priceLabel = label;
        }
    }
}

#pragma mark - 店主销售价
- (void)createLandlordBgView
{
    self.landlordBgView = [[UIView alloc]init];
    [self.view addSubview:self.landlordBgView];
    self.landlordBgView.frame = CGRectMake(0, self.priceBgView.bottom, SCREENWIDTH, 110);
    self.landlordBgView.backgroundColor = [UIColor whiteColor];
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 70)];
    [self.landlordBgView addSubview:topView];
    topView.backgroundColor = GrayTextColor;
    
    UILabel *landLordLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 70, 14)];
    [topView addSubview:landLordLabel];
    landLordLabel.font = FontWithSize(14);
    landLordLabel.textColor = BlackTextColor;
    landLordLabel.text = @"店主销售价";
    
    self.sectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, landLordLabel.bottom+5, 140, 10)];
    [topView addSubview:self.sectionLabel];
    self.sectionLabel.font = FontWithSize(10);
    self.sectionLabel.textColor = RGBACOLOR(130, 130, 130, 1);
    
    
    self.priceTF = [[UITextField alloc] initWithFrame:CGRectMake(SCREENWIDTH-15-90, 20, 90, 30)];
    [topView addSubview:self.priceTF];
    self.priceTF.backgroundColor = RGBACOLOR(252, 252, 252, 1);
    self.priceTF.font = FontMediumWithSize(20);
    self.priceTF.textAlignment = 1;
    self.priceTF.delegate = self;
    self.priceTF.keyboardType = UIKeyboardTypeDecimalPad;
    
    
//    self.lastLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, topView.bottom+10, 200, 10)];
//    [self.landlordBgView addSubview:self.lastLabel];
//    self.lastLabel.textColor = RGBACOLOR(130, 130, 130, 1);
//    self.lastLabel.font = FontWithSize(10);
}


//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
//    self.lastLabel.text = [NSString stringWithFormat:@"* 您上次销售价格为 ¥%0.2f 元",self.f_oldPrice];
//    [self.lastLabel sizeToFit];
//    return YES;
//}

#pragma mark - 编辑结束的时候
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSLog(@"编辑结束--%@",textField.text);
    if ([textField.text containsString:@"￥"])
    {
        textField.text = [textField.text stringByReplacingOccurrencesOfString:@"￥"withString:@""];
    }
    NSLog(@"编辑结束--%@",textField.text);
    
    CGFloat nowNumber = [textField.text floatValue];
    
    if (self.isHide)
    {
        //自营
        self.priceTF.text = [NSString stringWithFormat:@"￥%0.2f",nowNumber];
        [self.priceTF sizeToFit];
        self.f_newPrice = nowNumber;
        return YES;
    }
    else {
       //跨境
        if (nowNumber < self.f_shopCostPrice)
        {
            [self ShowHUDWithMessage:@"销售价低于成本价"];
            return NO;
        }
        else if (nowNumber > self.f_marketPrice)
        {
            [self ShowHUDWithMessage:@"销售价高于商品的市场价"];
            return NO;
        }else {
            self.priceTF.text = [NSString stringWithFormat:@"￥%0.2f",nowNumber];
            [self.priceTF sizeToFit];
            CGFloat earnings = nowNumber - [self.sharkModel.shopCostPrice floatValue];
            self.earningsLabel.text = [NSString stringWithFormat:@"￥%0.2f",earnings];
            
            self.f_newPrice = nowNumber;
            return YES;
        }
    }
    
}

#pragma mark - 分享图文选项
- (void)createShowImageTextView
{
    self.btnBgView = [[UIView alloc] init];
    [self.view addSubview:self.btnBgView];
    self.btnBgView.backgroundColor = GrayTextColor;
    self.btnBgView.frame = CGRectMake(0, self.landlordBgView.bottom, SCREENWIDTH, 90);
    
    NSInteger count = self.templatesArray.count;
    CGFloat jiange = (SCREENWIDTH-(60*count))/(count+1);
    
    for (int i = 0; i < count; i++)
    {
        TemplatesModel *model = self.templatesArray[i];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.btnBgView addSubview:button];
        button.tag = i+1;
        button.frame  = CGRectMake(jiange+(60+jiange)*(i%count), 15+(60+0)*(i/count), 60, 60);
        
        //设置图片
        [button sd_setImageWithURL:[NSURL URLWithString:model.icon] forState:UIControlStateNormal];
        [button sd_setImageWithURL:[NSURL URLWithString:model.selectIcon] forState:UIControlStateSelected];
        
        //设置文字
        [button setTitle:model.title forState:UIControlStateNormal];
        button.titleLabel.textAlignment = 1;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitleColor:RGBACOLOR(154, 154, 153, 1) forState:UIControlStateNormal];
        [button setTitleColor:BlackTextColor forState:UIControlStateSelected];
        
        //设置初始化选中项
        if (i == 0)
        {
            button.selected = YES;
            self.template_id = model.templateKey;//初始化模板id
            NSLog(@"模板ID-%@",model.ID);
        }
        
        // 获取button的宽高
        button.imageView.bounds = CGRectMake(0, 0, 30, 30);
        button.imageView.contentMode = UIViewContentModeScaleAspectFit;
        button.imageView.clipsToBounds = YES;
        CGFloat buttonHeight = CGRectGetHeight(button.bounds);
        CGFloat buttonWidth  = CGRectGetWidth(button.bounds);
        CGFloat buttonImageWidth  = CGRectGetWidth(button.imageView.bounds);
        NSLog(@"bounds--%@", NSStringFromCGRect(button.imageView.bounds));
        NSLog(@"buttonImageWidth--%f", buttonImageWidth);
        UIEdgeInsets edge = UIEdgeInsetsMake(0, (buttonWidth-buttonImageWidth)/2, 30, (buttonWidth-buttonImageWidth)/2);
        button.imageEdgeInsets = edge;
        button.titleEdgeInsets = UIEdgeInsetsMake(buttonHeight-edge.bottom+10, -buttonWidth/2, 5, 0);
        
        // 添加绑定事件
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UIButton *lookBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:lookBtn];
    lookBtn.frame = CGRectMake((SCREENWIDTH-80)/2, self.btnBgView.bottom+10, 80, 20);
    lookBtn.titleLabel.font = FontWithSize(10);
    [lookBtn setTitle:@"查看图片分享示例" forState:UIControlStateNormal];
    [lookBtn setTitleColor:RGBACOLOR(62, 141, 212, 1) forState:UIControlStateNormal];
    [lookBtn addTarget:self action:@selector(lookBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 分享&取消按钮
- (void)createSharkAndCancleBtn
{
    UIButton *sharkBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:sharkBtn];

    if (@available(iOS 11.0, *))
    {
        sharkBtn.frame = CGRectMake(15, SCREENHEIGHT-15-BottomHeight_xs-50, SCREENWIDTH-30, 50);
    } else {
        // Fallback on earlier versions
        sharkBtn.frame = CGRectMake(15, SCREENHEIGHT-15-BottomHeight-50, SCREENWIDTH-30, 50);
    }
    
    sharkBtn.layer.cornerRadius = 25;
    sharkBtn.layer.masksToBounds = YES;
    sharkBtn.backgroundColor = BtnBgColor;
    sharkBtn.titleLabel.font = FontWithSize(18);
    [sharkBtn setTitle:@"分享" forState:UIControlStateNormal];
    [sharkBtn setTitleColor:BlackTextColor forState:UIControlStateNormal];
    [sharkBtn addTarget:self action:@selector(sharkBtnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 图文，多图文，商品分享按钮点击事件
- (void)buttonClick:(UIButton *)sender
{
    //1，重置分享选项
    for (int i = 0; i < self.templatesArray.count; i++)
    {
        UIButton *button = [self.btnBgView viewWithTag:i+1];
        button.selected = NO;
    }
    sender.selected = YES;
    
    //2，改变模板id
    TemplatesModel *model = self.templatesArray[sender.tag-1];
    self.template_id = model.templateKey;//初始化模板id
    NSLog(@"模板ID-%@",model.templateKey);
}

#pragma mark - 查看分享示例
- (void)lookBtnClick:(UIButton *)sender
{
    NSLog(@"查看图片分享");
    SharkExampleVC *sharkExample = [[SharkExampleVC alloc] init];
    sharkExample.templatesArray = self.templatesArray;
    [self.navigationController pushViewController:sharkExample animated:YES];
}


#pragma mark - 分享按钮点击事件
- (void)sharkBtnBtnClick:(UIButton *)sender
{
    TranspondController *transpond = [[TranspondController alloc] init];
    transpond.price = [NSString stringWithFormat:@"%0.2f",self.f_newPrice];
    transpond.product_id = self.product_id;
    transpond.template_id = self.template_id;
//    transpond.shoppingDeailt = self.mainModel.name;
    [self.navigationController pushViewController:transpond animated:YES];
}

#pragma mark - 保证输入正确金额
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"%@---%@",textField.text, string);
    BOOL isHaveDian = YES;
    if ([textField.text rangeOfString:@"."].location==NSNotFound) {
        isHaveDian=NO;
    }
    if ([string length]>0)
    {
        unichar single=[string characterAtIndex:0];//当前输入的字符
        
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            //首字母不能为小数点
            if([textField.text length]==0){
                if(single == '.'){
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            if([textField.text length]==1 && [textField.text isEqualToString:@"0"]){
                if(single != '.'){
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            if (single=='.')
            {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian=YES;
                    return YES;
                }else
                {
                    [textField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            else
            {
                if (isHaveDian)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[textField.text rangeOfString:@"."];
                    NSInteger tt=range.location-ran.location;
                    if (tt <= 2){
                        return YES;
                    }else{
                        return NO;
                    }
                }
                else
                {
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            [textField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
    
}

@end
